import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue';
import Components from 'unplugin-vue-components/vite';
import { VantResolver } from 'unplugin-vue-components/resolvers';
// https://vitejs.dev/config/

// 判断当前环境 - 这只适用于开发服务器
const isDev = process.env.NODE_ENV === 'development';
// 使用内网穿透配置
const isTunnel = true; // 启用内网穿透模式

// 配置服务器地址
const targetServer = isDev 
  ? 'http://localhost:8080' 
  : (isTunnel ? 'http://47.109.146.201:6100' : 'http://47.109.146.201:6100');
  
// 配置WebSocket地址  
const wsServer = isDev 
  ? 'ws://localhost:8080' 
  : (isTunnel ? 'ws://47.109.146.201:6401' : 'ws://47.109.146.201:6401');

console.log('Vite配置 - API服务器:', targetServer);
console.log('Vite配置 - WebSocket服务器:', wsServer);

export default defineConfig({
    base: '/',
    plugins: [
        vue(),
        Components({
            resolvers: [VantResolver()],
        }),
    ],
    server: {
        port: 5173,
        host: '0.0.0.0',
        proxy: {
            '/api': {
                target: targetServer,
                changeOrigin: true,
                secure: false,
                rewrite: (path) => path.replace(/^\/api/, '/api'),
                configure: (proxy, options) => {
                    proxy.on('proxyReq', (proxyReq, req, res) => {
                        proxyReq.setHeader('Origin', isDev ? 'http://localhost:5173' : 'http://47.109.146.201:6200');
                    });
                }
            },
            '/websocket': {
                target: wsServer,
                ws: true,
                changeOrigin: true,
                secure: false,
                rewrite: (path) => path.replace(/^\/websocket/, '/websocket')
            }
        }
    },
    // 确保构建时的环境变量正确
    define: {
        // 注意：必须使用字符串值
        'process.env.API_ENV': JSON.stringify(process.env.NODE_ENV),
        'process.env.TUNNEL_ENABLED': JSON.stringify(isTunnel)
    }
})
